// 全局变量：当前操作的教师ID
let currentTeacherId = null;

// 模态框状态枚举
const ModalState = {
    ADD: 'add',
    EDIT: 'edit'
};

// 显示通知提示
function showToast(message, type = 'success') {
    const toast = document.createElement('div');
    toast.className = `fixed top-4 right-4 p-3 rounded-lg shadow-lg z-50 transform transition-all duration-300 ease-in-out ${
        type === 'success' ? 'bg-green-500 text-white' : 'bg-red-500 text-white'
    }`;
    toast.textContent = message;
    toast.style.transform = 'translateY(-20px)'; // 初始位置
    document.body.appendChild(toast);

    // 触发动画
    setTimeout(() => toast.style.transform = 'translateY(0)', 10);

    // 3秒后隐藏并移除
    setTimeout(() => {
        toast.style.transform = 'translateY(-20px)';
        toast.style.opacity = '0';
        setTimeout(() => document.body.removeChild(toast), 300);
    }, 3000);
}

// 显示表单错误信息
function showErrors(errors) {
    clearFormErrors();
    Object.entries(errors).forEach(([field, msg]) => {
        const errorEl = document.getElementById(`${field}Error`);
        const inputEl = document.getElementById(field);

        if (errorEl) {
            errorEl.textContent = msg;
            errorEl.classList.remove('hidden');
        }

        if (inputEl) {
            inputEl.classList.add('border-red-500');

            // 添加错误输入框的抖动动画
            inputEl.classList.add('animate-shake');
            setTimeout(() => inputEl.classList.remove('animate-shake'), 500);
        }
    });
}

// 清除表单错误信息
function clearFormErrors() {
    document.querySelectorAll('[id$="Error"]').forEach(el => {
        el.textContent = '';
        el.classList.add('hidden');
    });

    document.querySelectorAll('input, select').forEach(el => {
        el.classList.remove('border-red-500', 'animate-shake');
    });
}

// 设置模态框状态（添加/编辑）
function setModalState(state) {
    const saveButton = document.getElementById('saveButton');
    const teacherNoInput = document.getElementById('teacherNo');

    if (saveButton) {
        saveButton.textContent = state === ModalState.ADD ? '新增' : '更新';
        saveButton.classList.toggle('bg-blue-500', state === ModalState.ADD);
        saveButton.classList.toggle('bg-green-500', state === ModalState.EDIT);
    }

    if (teacherNoInput) {
        teacherNoInput.readOnly = state === ModalState.EDIT;
        teacherNoInput.classList.toggle('bg-gray-100', state === ModalState.EDIT);
    }
}

// 重置表单
function resetForm() {
    const teacherForm = document.getElementById('teacherForm');
    if (teacherForm) {
        teacherForm.reset();
        document.querySelectorAll('select').forEach(select => select.selectedIndex = 0);
        clearFormErrors();
    }
}

// 完全重置（用于添加模式）
function fullyResetForm() {
    currentTeacherId = null;
    resetForm();
}

// ---------------------- 添加教师功能 ----------------------
// 添加教师模态框打开
function openAddModal() {
    fullyResetForm();
    setModalState(ModalState.ADD);
    showModal('新增教师');

    // 自动聚焦第一个输入框
    setTimeout(() => {
        document.getElementById('teacherNo')?.focus();
    }, 300);
}

// 处理添加请求
function handleAddTeacher() {
    console.log('执行添加操作');
    const formData = new FormData(document.getElementById('teacherForm'));
    const errors = validateForm(formData, ModalState.ADD);

    if (Object.keys(errors).length > 0) {
        showErrors(errors);
        return;
    }

    sendRequest('/admin/add_teacher', 'POST', buildTeacherData(formData));
}

// ---------------------- 编辑教师功能 ----------------------
// 编辑教师模态框打开
function openEditModal(id) {
    console.log('打开编辑模态框，ID:', id);
    currentTeacherId = id;
    resetForm();
    setModalState(ModalState.EDIT);
    showModal('编辑教师');
    setPasswordRequired(false);
    fetchTeacherData(id);
}

// 处理编辑请求
function handleUpdateTeacher() {
    if (!currentTeacherId) {
        showToast('请选择要编辑的教师', 'error');
        return;
    }

    console.log('执行更新操作，ID:', currentTeacherId);
    const formData = new FormData(document.getElementById('teacherForm'));
    const errors = validateForm(formData, ModalState.EDIT);

    if (Object.keys(errors).length > 0) {
        showErrors(errors);
        return;
    }

    sendRequest(`/admin/teacher/${currentTeacherId}`, 'PUT', buildTeacherData(formData));
}

// ---------------------- 删除教师功能 ----------------------
// 确认删除
function confirmDelete(id) {
    if (!confirm('确认删除该教师？此操作不可恢复')) return;
    handleDeleteTeacher(id);
}

// 处理删除请求
function handleDeleteTeacher(id) {
    const btn = event.target.closest('button');
    if (!btn) return;

    btn.disabled = true;
    btn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 删除中...';

    fetch(`/admin/teacher/${id}`, { method: 'DELETE' })
        .then(response => {
            if (!response.ok) throw new Error(`删除失败：${response.status}`);
            return response.json();
        })
        .then(result => {
            if (result.success) {
                showToast(result.message, 'success');
                removeTeacherFromTable(id);

                // 延迟刷新页面，让用户有时间看到成功提示
                setTimeout(() => {
                    window.location.reload();
                }, 1500);
            } else {
                showToast(result.message, 'error');
            }
        })
        .catch(error => {
            console.error('删除教师错误:', error);
            showToast('删除失败，请重试', 'error');
        })
        .finally(() => {
            btn.disabled = false;
            btn.innerHTML = '<i class="fa fa-trash-alt mr-1"></i> 删除';
        });
}

// ---------------------- 公共辅助方法 ----------------------
// 设置密码字段的必填状态
function setPasswordRequired(required) {
    const passwordInput = document.getElementById('password');
    const passwordGroup = passwordInput?.closest('.form-group');

    if (passwordInput) {
        passwordInput.required = required;
        passwordInput.placeholder = required
            ? '请输入密码（6-120位）'
            : '留空则不修改密码';
    }

    // 编辑模式下隐藏密码字段提示
    if (passwordGroup && !required) {
        const hintEl = passwordGroup.querySelector('.password-hint');
        if (hintEl) hintEl.textContent = '（留空则不修改密码）';
    }
}

// 发送HTTP请求
function sendRequest(url, method, data) {
    const saveButton = document.getElementById('saveButton');
    saveButton.disabled = true;
    saveButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 处理中...';

    // 添加请求拦截器：添加认证信息（如果有）
    const headers = { 'Content-Type': 'application/json' };
    const token = localStorage.getItem('auth_token'); // 从本地存储获取token
    if (token) headers['Authorization'] = `Bearer ${token}`;

    fetch(url, {
        method,
        headers,
        body: JSON.stringify(data)
    })
    .then(response => {
        // 统一处理HTTP错误
        if (!response.ok) {
            throw new Error(`HTTP错误：${response.status} ${response.statusText}`);
        }
        return response.json();
    })
    .then(result => {
        if (result.success) {
            showToast(result.message, 'success');
            closeModal(); // 关闭模态框

            // 延迟刷新页面，让用户有时间看到成功提示
            setTimeout(() => {
                // 刷新当前页面或执行回调函数
                window.location.reload();
            }, 1500);
        } else {
            showToast(result.message, 'error');

            // 处理特定错误类型
            if (result.error === 'teacher_no_exists') {
                document.getElementById('teacherNoError')?.classList.remove('hidden');
                document.getElementById('teacherNo')?.classList.add('border-red-500');
            }

            // 如果返回表单验证错误，显示错误信息
            if (result.errors) {
                showErrors(result.errors);
            }
        }
    })
    .catch(error => {
        // 统一处理网络错误
        console.error('请求异常:', error);

        // 显示友好的错误信息
        let errorMessage = '网络请求失败，请重试';
        if (error.message.includes('Failed to fetch')) {
            errorMessage = '网络连接失败，请检查网络设置';
        }

        showToast(errorMessage, 'error');
    })
    .finally(() => {
        // 无论请求成功或失败，都恢复按钮状态
        saveButton.disabled = false;
        saveButton.textContent = currentTeacherId ? '更新' : '新增';
    });
}

// 获取教师数据
function fetchTeacherData(id) {
    console.log('开始获取教师数据，ID:', id);

    // 添加请求拦截器：添加认证信息（如果有）
    const headers = {};
    const token = localStorage.getItem('auth_token');
    if (token) headers['Authorization'] = `Bearer ${token}`;

    fetch(`/admin/teacher/${id}`, {
        method: 'GET',
        headers
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`获取教师信息失败：${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        if (!data.success) {
            throw new Error(data.message);
        }

        console.log('成功获取教师数据，ID:', id);
        // 格式化日期并填充表单
        fillForm(formatTeacherData(data.data));
    })
    .catch(error => {
        console.error('获取教师信息错误:', error);
        showToast('获取教师信息失败，请重试', 'error');
        // 加载失败时重置为添加模式
        currentTeacherId = null;
        setModalState(ModalState.ADD);
    });
}

// 格式化教师数据（主要处理日期格式）
function formatTeacherData(teacher) {
    // 确保日期格式正确（YYYY-MM-DD）
    if (teacher.hire_date) {
        // 如果日期是ISO格式，提取日期部分
        if (teacher.hire_date.includes('T')) {
            teacher.hire_date = teacher.hire_date.split('T')[0];
        }
        // 如果日期是时间戳，转换为YYYY-MM-DD格式
        else if (typeof teacher.hire_date === 'number') {
            const date = new Date(teacher.hire_date);
            teacher.hire_date = date.toISOString().split('T')[0];
        }
    }

    return teacher;
}

// 填充表单数据
function fillForm(teacher) {
    console.log('填充表单数据，教师:', teacher);

    document.getElementById('teacherId').value = teacher.id;
    document.getElementById('teacherNo').value = teacher.teacher_no;
    document.getElementById('username').value = teacher.username;
    document.getElementById('title').value = teacher.title;
    document.getElementById('department').value = teacher.department;
    document.getElementById('hireDate').value = teacher.hire_date || '';
    document.getElementById('email').value = teacher.email || '';
    document.getElementById('telephone').value = teacher.telephone || '';
    document.getElementById('address').value = teacher.address || '';
    // 注意：密码不应该填充，保持为空或提示
    document.getElementById('password').value = teacher.password || '';

    // 触发输入框的change事件，更新UI状态
    document.querySelectorAll('input, select').forEach(input => {
        const event = new Event('change');
        input.dispatchEvent(event);
    });
}

// 表单验证
function validateForm(formData, operation) {
    const errors = {};

    // 根据操作类型（添加/编辑）确定必填字段
    const requiredFields = ['username', 'title', 'department', 'hireDate'];

    if (operation === ModalState.ADD) {
        requiredFields.push('teacherNo', 'password');
    }

    // 验证必填字段
    requiredFields.forEach(field => {
        if (!formData.get(field)) {
            errors[field] = `请填写 ${getFieldLabel(field)}`;
        }
    });

    // 验证工号格式
    if (operation === ModalState.ADD || formData.get('teacherNo')) {
        const teacherNo = formData.get('teacherNo');
        if (teacherNo && !/^T\d+$/.test(teacherNo)) {
            errors.teacherNo = '工号需以T开头，后跟数字';
        }
    }

    // 验证密码
    const password = formData.get('password');
    if ((operation === ModalState.ADD || password) && password) {
        if (password.length < 6 || password.length > 120) {
            errors.password = '密码长度需为6-120位';
        }
    }

    // 验证邮箱格式
    const email = formData.get('email');
    if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        errors.email = '请输入有效的邮箱地址';
    }

    // 验证电话号码格式
    const telephone = formData.get('telephone');
    if (telephone && !/^1[3-9]\d{9}$/.test(telephone)) {
        errors.telephone = '请输入有效的手机号码';
    }

    // 验证入职日期
    const hireDate = formData.get('hireDate');
    if (hireDate) {
        const today = new Date();
        today.setHours(0, 0, 0, 0);

        const inputDate = new Date(hireDate);
        inputDate.setHours(0, 0, 0, 0);

        if (inputDate > today) {
            errors.hireDate = '入职日期不能晚于今天';
        }
    }

    return errors;
}

// 获取字段标签名称
function getFieldLabel(field) {
    return {
        teacherNo: '工号',
        username: '姓名',
        title: '职称',
        department: '部门',
        hireDate: '入职日期',
        password: '密码',
        email: '邮箱',
        telephone: '电话',
        address: '地址'
    }[field] || '字段';
}

// 更新教师表格
function updateTeacherTable(teachers) {
    const tbody = document.querySelector('tbody');

    if (!teachers || teachers.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="6" class="text-center p-6 text-gray-500">
                    <i class="fa fa-info-circle mr-2"></i>暂无教师记录
                </td>
            </tr>
        `;
        return;
    }

    tbody.innerHTML = teachers.map(teacher => `
        <tr data-id="${teacher.id}" class="hover:bg-gray-50 transition-colors">
            <td class="px-4 py-3">${teacher.teacher_no}</td>
            <td class="px-4 py-3">${teacher.username}</td>
            <td class="px-4 py-3">${teacher.title}</td>
            <td class="px-4 py-3">${teacher.department}</td>
            <td class="px-4 py-3">${teacher.email || '<span class="text-gray-400">未填写</span>'}</td>
            <td class="px-4 py-3 text-right">
                <button onclick="openEditModal(${teacher.id})" 
                    class="text-primary hover:text-primary/70 mr-2 transition-colors">
                    <i class="fa fa-pen-alt mr-1"></i> 编辑
                </button>
                <button onclick="confirmDelete(${teacher.id})" 
                    class="text-red-500 hover:text-red-700 transition-colors">
                    <i class="fa fa-trash-alt mr-1"></i> 删除
                </button>
            </td>
        </tr>
    `).join('');
}

// 从表格中移除教师行
function removeTeacherFromTable(id) {
    const row = document.querySelector(`[data-id="${id}"]`);

    if (row) {
        // 添加淡出动画
        row.style.opacity = '0';
        row.style.transform = 'translateX(20px)';
        row.style.transition = 'opacity 0.3s, transform 0.3s';

        setTimeout(() => {
            row.remove();
        }, 300);
    }
}

// 显示模态框
function showModal(title) {
    const modal = document.getElementById('modal');

    if (modal) {
        modal.querySelector('#modalTitle').textContent = title;

        // 显示模态框并添加动画
        modal.classList.remove('opacity-0', 'pointer-events-none');
        modal.querySelector('#modalContent').classList.remove('scale-95');
        modal.querySelector('#modalContent').classList.add('scale-100');

        // 禁止背景滚动
        document.body.style.overflow = 'hidden';

        // 添加模态框背景点击关闭功能
        modal.onclick = function(event) {
            if (event.target === modal) {
                closeModal();
            }
        };
    }
}

// 关闭模态框
function closeModal() {
    const modalContent = document.getElementById('modalContent');

    if (modalContent) {
        // 添加关闭动画
        modalContent.classList.remove('scale-100');
        modalContent.classList.add('scale-95');

        setTimeout(() => {
            const modal = document.getElementById('modal');
            if (modal) {
                modal.classList.add('opacity-0', 'pointer-events-none');

                // 恢复背景滚动
                document.body.style.overflow = '';

                // 重置表单
                resetForm();
            }
        }, 300); // 等待动画完成
    }
}

// 构建教师数据对象
function buildTeacherData(formData) {
    return {
        teacher_no: formData.get('teacherNo'),
        username: formData.get('username'),
        title: formData.get('title'),
        department: formData.get('department'),
        hire_date: formData.get('hireDate'),
        email: formData.get('email'),
        telephone: formData.get('telephone'),
        address: formData.get('address'),
        password: formData.get('password') || null
    };
}

// 获取所有教师数据
function fetchAllTeachers() {
    fetch('/admin/teachers', { method: 'GET' })
    .then(response => {
        if (!response.ok) throw new Error(`获取教师列表失败：${response.status}`);
        return response.json();
    })
    .then(data => {
        if (data.success) {
            updateTeacherTable(data.data);
        } else {
            showToast(data.message, 'error');
        }
    })
    .catch(error => {
        console.error('获取教师列表错误:', error);
        showToast('获取教师列表失败，请重试', 'error');
    });
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    console.log('DOM加载完成，初始化教师管理系统');

    // 初始化添加教师按钮
    const addTeacherBtn = document.getElementById('addTeacherBtn');
    addTeacherBtn?.addEventListener('click', openAddModal);

    // 初始化保存按钮
    const saveButton = document.getElementById('saveButton');
    saveButton?.addEventListener('click', () => {
        console.log('保存按钮点击，当前ID:', currentTeacherId);
        currentTeacherId ? handleUpdateTeacher() : handleAddTeacher();
    });

    // 初始化密码显示/隐藏按钮
    document.querySelectorAll('.toggle-password').forEach(btn => {
        btn.addEventListener('click', () => {
            const input = btn.closest('.relative').querySelector('input');
            const icon = btn.querySelector('i');

            if (input) {
                input.type = input.type === 'password' ? 'text' : 'password';

                // 切换图标
                if (input.type === 'text') {
                    icon.classList.remove('fa-eye-slash');
                    icon.classList.add('fa-eye');
                } else {
                    icon.classList.remove('fa-eye');
                    icon.classList.add('fa-eye-slash');
                }
            }
        });
    });

    // 初始化表单输入框的实时验证
    document.querySelectorAll('#teacherForm input, #teacherForm select').forEach(input => {
        input.addEventListener('blur', () => {
            // 实时验证当前字段
            const formData = new FormData(document.getElementById('teacherForm'));
            const operation = currentTeacherId ? ModalState.EDIT : ModalState.ADD;
            const errors = validateForm(formData, operation);

            // 显示或清除当前字段的错误
            if (errors[input.id]) {
                showErrors({ [input.id]: errors[input.id] });
            } else {
                const errorEl = document.getElementById(`${input.id}Error`);
                if (errorEl) {
                    errorEl.textContent = '';
                    errorEl.classList.add('hidden');
                }
                input.classList.remove('border-red-500');
            }
        });
    });

    // 初始化日期选择器的最大日期为今天
    const hireDateInput = document.getElementById('hireDate');
    if (hireDateInput) {
        const today = new Date().toISOString().split('T')[0];
        hireDateInput.max = today;
    }


});

// 添加抖动动画样式
const style = document.createElement('style');
style.textContent = `
    @keyframes shake {
        0%, 100% { transform: translateX(0); }
        10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
        20%, 40%, 60%, 80% { transform: translateX(5px); }
    }
    
    .animate-shake {
        animation: shake 0.5s cubic-bezier(.36,.07,.19,.97) both;
    }
`;
document.head.appendChild(style);